package com.yupi.yuojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.StatsCmd;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.yupi.yuojcodesandbox.model.ExecuteCodeRequest;
import com.yupi.yuojcodesandbox.model.ExecuteCodeResponse;
import com.yupi.yuojcodesandbox.model.ExecuteMessage;
import com.yupi.yuojcodesandbox.model.JudgeInfo;
import com.yupi.yuojcodesandbox.utils.ProcessUtils;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class JavaDockerCodeSandOldbox implements CodeSandbox{
    public static final String GLOBAL_CODE_DIR_NAME="tmpCode"; //全局代码存放目录
    public static final String GLOBAL_JAVA_CLASS_NAME="Main.java";//全局类名
    public static final long  TIME_OUT=5000L;
    public static final List<String> blackList=Arrays.asList("Files","exec");

    public static final Boolean FIRST_INT=true;
    public static void main(String[] args) {
        JavaDockerCodeSandOldbox javaNativeCodeSandbox = new JavaDockerCodeSandOldbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setInputList(Arrays.asList("100 2","32 4"));
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        //权限管理
//        System.setSecurityManager(new DefaultSecutityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code= executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //1.把用户代码保存为文件
        String userDir=System.getProperty("user.dir");
        String globalCodePathNmae=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在,不存在则新建
        if(!FileUtil.exist(globalCodePathNmae)){
            FileUtil.mkdir(globalCodePathNmae);
        }
        //把用户代码隔离存放
        String uuID= String.valueOf(UUID.randomUUID());
        String userCodeParentPath=globalCodePathNmae+File.separator+ uuID;
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        System.out.println(userCodeParentPath);
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2.编译代码,得到class文件
        String compiledCmd=String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        try {
            Process compileProcess=Runtime.getRuntime().exec(compiledCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess,"编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return   getErrorResponse(e);
        }

        // 配置Docker客户端连接到守护进程的地址
        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("tcp://192.168.88.100:2375")
                // 或者对于Windows，如果你已经设置了TCP连接，可以是 "tcp://localhost:2375"
                .build();
        // 使用配置创建Docker客户端实例
        DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

        String image="openjdk:8-alpine";
        //如果拉取过镜像,就跳过
//        if(FIRST_INT){
//            //拉取镜像
//            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
//            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
//                @Override
//                public void onNext(PullResponseItem item){
//                    System.out.println("下载镜像:"+item.getStatus());
//                    super.onNext(item);
//                }
//            };
//            try {
//                pullImageCmd
//                        .exec(pullImageResultCallback)
//                        .awaitCompletion();
//            } catch (InterruptedException e) {
//                System.out.println("拉取镜像异常");
//                throw new RuntimeException(e);
//            }
//        }
        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        //配置容器
        HostConfig hostConfig=new HostConfig();
        //容器内存限制
        hostConfig.withMemory(100*1000*1000L);
        hostConfig.withMemorySwap(0L);
        //容器cpu限制
        hostConfig.withCpuCount(1L);
        //指定文件路径,和容器内存放文件路径,把虚拟机里的文件挂载到容器上
      String  linuxUserCodeParentPath="/home/jizhaosai/yuoj-code-sandbox/tmpCode/"+uuID;
        Bind bind = new Bind(linuxUserCodeParentPath, new Volume("/app"));
        hostConfig.setBinds(bind);
        CreateContainerResponse createContainerResponse=containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)   //静止容器联网
                .withReadonlyRootfs(true)   //限制用户不能向根目录写文件
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId=createContainerResponse.getId();
        //启动容器
         dockerClient.startContainerCmd(containerId).exec();
//        执行容器中的java文件
//        docker exec  eloquent_cartwright java -cp /app Main 13 14
        //等待容器中的文件Main同步,延迟很高
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //执行命令并获取输出
        List<ExecuteMessage>executeMessageList=new ArrayList<>();

        for (String inputArgs : inputList) {
            //创建一个定时器,用于记录执行时间
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray=inputArgs.split(" ");
            String[] cmdArray= ArrayUtil.append(new String[]{"java","-cp","/app","Main"},inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse =dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            //启动的是tty可交互式的容器
            System.out.println("命令: "+ Arrays.toString(cmdArray));
            System.out.println("容器的id:"+containerId);
            System.out.println("创建执行命令: "+execCreateCmdResponse);
            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time=0L;
            final boolean[] timeout = {true}; //判断是否执行超时
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(){
                @Override
                public void onComplete(){
                    //如果执行完成,则表示没超时
                    timeout[0] =false;
                    super.onComplete();
                }
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if(StreamType.STDERR.equals(streamType)){
                        message[0] =new String(frame.getPayload());
                        System.out.println("输出错误结果: "+ message[0]);
                    }else {
                        errorMessage[0] =new String(frame.getPayload());
                        System.out.println("输出结果: "+ errorMessage[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};
            //获取占用内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用: " + statistics.getMemoryStats().getUsage());
                    maxMemory[0] =Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);

            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                stopWatch.stop();
                time= stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }

        //4.收集整理输出
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outPutList=new ArrayList<>();
        //最大运行时间
        long maxTime=0;
        //最大运行内存
        long maxMemory=0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(1);
                break;
            }
            outPutList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            Long memory=executeMessage.getMemory();
            if(memory!=null){
                maxMemory=Math.max(maxMemory,memory);
            }
            if(time!=null){
                maxTime=Math.max(maxTime,time);
            }
        }
        //正常运行完成
        if(outPutList.size()==executeMessageList.size()){
            executeCodeResponse.setStatus(3);
        }
        executeCodeResponse.setOutputList(outPutList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        //5.文件清理,防止服务器空间不足
        if(userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del ? "成功":"失败"));
        }
        return executeCodeResponse;
}

    public ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
